package com.kurt.controller;

import com.kurt.annotation.Log;
import com.kurt.common.PageResult;
import com.kurt.common.Result;
import com.kurt.dto.SysConfigDTO;
import com.kurt.dto.create.SysConfigCreateRequest;
import com.kurt.dto.query.SysConfigQueryRequest;
import com.kurt.dto.update.SysConfigUpdateRequest;
import com.kurt.entity.SysConfig;
import com.kurt.service.SysConfigService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 系统配置控制器
 * 处理系统配置相关的HTTP请求
 */
@Slf4j
@RestController
@RequestMapping("/configs")
@RequiredArgsConstructor
public class SysConfigController extends BaseController {

    private final SysConfigService configService;

    /**
     * 创建系统配置
     *
     * @param createRequest 创建请求
     * @return 配置信息
     */
    @PostMapping
    @Log(title = "系统配置管理", businessType = 1, operatorType = 1)
    public Result<SysConfigDTO> createConfig(@RequestBody SysConfigCreateRequest createRequest) {
        try {
            createRequest.setCreateUserId(getCurrentUserId());
            log.info("创建系统配置请求: {}", createRequest.getConfigKey());
            SysConfigDTO config = configService.createConfig(createRequest);
            return Result.success("创建成功", config);
        } catch (Exception e) {
            log.error("创建系统配置失败: {}", e.getMessage(), e);
            return Result.error("创建失败: " + e.getMessage());
        }
    }

    /**
     * 更新系统配置
     *
     * @param updateRequest 更新请求
     * @return 配置信息
     */
    @PutMapping
    @Log(title = "系统配置管理", businessType = 2, operatorType = 1)
    public Result<SysConfigDTO> updateConfig(@RequestBody SysConfigUpdateRequest updateRequest) {
        try {
            updateRequest.setUpdateUserId(getCurrentUserId());
            log.info("更新系统配置请求: {}", updateRequest.getId());
            SysConfigDTO config = configService.updateConfig(updateRequest);
            return Result.success("更新成功", config);
        } catch (Exception e) {
            log.error("更新系统配置失败: {}", e.getMessage(), e);
            return Result.error("更新失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID获取配置详情
     *
     * @param id 配置ID
     * @return 配置信息
     */
    @GetMapping("/{id}")
    public Result<SysConfig> getConfigById(@PathVariable("id") Long id) {
        try {
            log.info("获取配置详情请求: {}", id);
            SysConfig config = configService.getById(id);
            return Result.success("获取成功", config);
        } catch (Exception e) {
            log.error("获取配置详情失败: {}", e.getMessage(), e);
            return Result.error("获取失败: " + e.getMessage());
        }
    }

    /**
     * 分页查询系统配置
     *
     * @param queryRequest 查询请求
     * @return 分页结果
     */
    @PostMapping("/page")
    public Result<PageResult<SysConfigDTO>> getConfigPage(@RequestBody SysConfigQueryRequest queryRequest) {
        try {
            queryRequest.setLoginUserId(getCurrentUserId());
            log.info("分页查询系统配置请求: {}", queryRequest);
            Page<SysConfigDTO> configPage = configService.getConfigPage(queryRequest);

            // 转换为PageResult
            PageResult<SysConfigDTO> pageResult = PageResult.of(
                    queryRequest.getPageNum(),
                    queryRequest.getPageSize(),
                    configPage.getTotalElements(),
                    configPage.getContent()
            );

            return Result.success("分页查询成功", pageResult);
        } catch (Exception e) {
            log.error("分页查询系统配置失败: {}", e.getMessage(), e);
            return Result.error("分页查询失败: " + e.getMessage());
        }
    }

    /**
     * 查询系统配置列表
     *
     * @param queryRequest 查询请求
     * @return 配置列表
     */
    @PostMapping("/list")
    public Result<List<SysConfigDTO>> getConfigList(@RequestBody SysConfigQueryRequest queryRequest) {
        try {
            queryRequest.setLoginUserId(getCurrentUserId());
            log.info("查询系统配置列表请求: {}", queryRequest);
            List<SysConfigDTO> configs = configService.getConfigList(queryRequest);
            return Result.success("查询成功", configs);
        } catch (Exception e) {
            log.error("查询系统配置列表失败: {}", e.getMessage(), e);
            return Result.error("查询失败: " + e.getMessage());
        }
    }

    /**
     * 根据配置键名获取配置值
     *
     * @param configKey 配置键名
     * @return 配置值
     */
    @GetMapping("/value/{configKey}")
    public Result<String> getConfigValue(@PathVariable("configKey") String configKey) {
        try {
            log.info("获取配置值请求: {}", configKey);
            String value = configService.getConfigValue(configKey);
            return Result.success("获取成功", value);
        } catch (Exception e) {
            log.error("获取配置值失败: {}", e.getMessage(), e);
            return Result.error("获取失败: " + e.getMessage());
        }
    }

    /**
     * 根据配置键名获取配置对象
     *
     * @param configKey 配置键名
     * @return 配置对象
     */
    @GetMapping("/key/{configKey}")
    public Result<SysConfigDTO> getConfigByKey(@PathVariable("configKey") String configKey) {
        try {
            log.info("根据键名获取配置请求: {}", configKey);
            SysConfigDTO config = configService.getConfigByKey(configKey);
            return Result.success("获取成功", config);
        } catch (Exception e) {
            log.error("根据键名获取配置失败: {}", e.getMessage(), e);
            return Result.error("获取失败: " + e.getMessage());
        }
    }

    /**
     * 删除系统配置
     *
     * @param id 配置ID
     * @return 删除结果
     */
    @DeleteMapping("/{id}")
    @Log(title = "系统配置管理", businessType = 3, operatorType = 1)
    public Result<Boolean> deleteConfig(@PathVariable("id") Long id) {
        try {
            log.info("删除系统配置请求: {}", id);
            boolean success = configService.deleteById(id);
            return Result.success("删除成功", success);
        } catch (Exception e) {
            log.error("删除系统配置失败: {}", e.getMessage(), e);
            return Result.error("删除失败: " + e.getMessage());
        }
    }

    /**
     * 批量删除系统配置
     *
     * @param ids 配置ID列表
     * @return 删除结果
     */
    @DeleteMapping("/batch")
    @Log(title = "系统配置管理", businessType = 3, operatorType = 1)
    public Result<Boolean> deleteConfigs(@RequestBody List<Long> ids) {
        try {
            log.info("批量删除系统配置请求: {}", ids);
            boolean success = configService.deleteConfigs(ids);
            return Result.success("批量删除成功", success);
        } catch (Exception e) {
            log.error("批量删除系统配置失败: {}", e.getMessage(), e);
            return Result.error("批量删除失败: " + e.getMessage());
        }
    }

    /**
     * 检查配置键名是否存在
     *
     * @param configKey 配置键名
     * @return 是否存在
     */
    @GetMapping("/exists/{configKey}")
    public Result<Boolean> existsByConfigKey(@PathVariable("configKey") String configKey) {
        try {
            log.info("检查配置键名是否存在请求: {}", configKey);
            boolean exists = configService.existsByConfigKey(configKey);
            return Result.success("检查成功", exists);
        } catch (Exception e) {
            log.error("检查配置键名是否存在失败: {}", e.getMessage(), e);
            return Result.error("检查失败: " + e.getMessage());
        }
    }
}
